package 链表;

public class LinkList<E> {
    private int size;
    private Node<E> first;
    private Node<E> last;

    private static class Node<E>{
        E element;
        Node<E> next;
        Node<E> prev;
        public Node(E element,Node<E> next,Node<E> prev) {
            this.element = element;
            this.next = next;
            this.prev = prev;
        }
    }

    public Node<E> get(int index){
        Node<E> node = get_node(index);
        return node;
    }

    public E set(int index,E element){
        Node<E> node = get_node(index);
        E old_value = node.element;
        node.element = element;
        return old_value;
    }

    public void add(int index,E element){
        CheckRangeForAdd(index);

        Node<E> new_node_next = get_node(index);
        Node<E> new_node_prev = new_node_next.prev;
        Node<E> new_node = new Node<>(element,new_node_next,null);
        new_node_next.prev = new_node;

        if (new_node_prev == null){
            first = new_node;
        }else {
            new_node_prev.next = new_node;
        }
        size++;

    }

    public void clear(){
        size = 0;
        first = null;
        last = null;

    }

    public Node<E> get_node(int index){
        CheckRange(index);
        if (index < size/2){
            Node<E> cur_node = first;
            for (int i = 0;i < index;i++){
                cur_node = cur_node.next;
            }
//            if (cur_node == null){
//                cur_node.element = null;
//            }
            return cur_node;
        }
        else {
            Node<E> cur_node = last;
            for (int i = size -1;i > index;i--){
                cur_node = cur_node.prev;
            }
//            if (cur_node == null){
//                cur_node.element = null;
//            }
            return cur_node;
        }

    }

    public void CheckRange(int index){
        if (index >= size && index < 0){
            throw new IndexOutOfBoundsException("异常提醒：你的下标好像越界了");
        }
    }

    public void CheckRangeForAdd(int index){
        if (index > size && index < 0){
            throw new IndexOutOfBoundsException("异常提醒：你的下标好像越界了");
        }
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        str.append("[");
        Node<E> cur_node = first;
        for (int i = 0;i<size;i++){
            str.append(first+",");
            cur_node = cur_node.next;
            if (cur_node.next == null){
                str.append(cur_node);
            }
        }
        str.append("]");
        return str.toString();
    }
}
